package com.sjzd.weixin.task;

import com.alibaba.fastjson.JSONObject;
import com.sjzd.meeting.service.IMeetingPublishService;
import com.sjzd.weixin.bean.message.custom.Text;
import com.sjzd.weixin.bean.message.custom.TextMessage;
import com.sjzd.weixin.menu.MenuManager;
import com.sjzd.weixin.utils.WxUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 *  每隔两小时刷新access_token（接口令牌）以及菜单
 */
@Component
public class ScheduleTask {
    private static final Logger log = LoggerFactory.getLogger(ScheduleTask.class);

    @Value("${wx.appID}")
    private String appId;
    @Value("${wx.appsecret}")
    private String secret;
    @Autowired
    private MenuManager menuManager;
    @Autowired
    private IMeetingPublishService meetingPublishService;

    // 客服接口-发消息接口调用请求url模板
    private static final String custom_send_url_format = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s";

    /**
     *  每日定时发送订单消息
     */
    @Scheduled(cron = "0 0 8 * * ?")
    public void sendEveryNews() {
        String accessToken = WxUtils.getAccessToken();
        String url = String.format(custom_send_url_format, accessToken);
        String content = meetingPublishService.everyNews();
        TextMessage textMessage = new TextMessage();
        textMessage.setTouser("o5XInwP8OmCPfl55McnNeLAmy9PI");
        textMessage.setMsgtype("text");
        Text text = new Text();
        text.setContent(content);
        textMessage.setText(text);
        String msg = JSONObject.toJSON(textMessage).toString();
        WxUtils.httpRequest(url, "POST", msg);
    }


    @Scheduled(fixedDelay = 1000 * 3600 * 2)
    public void refreshAccessToken() {
        WxUtils.refreshAccessToken(appId, secret);
        WxUtils.refreshMenu(menuManager.buildMenu());
        log.info("刷新access_token一次");
    }
}